﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using DotNetCoreStudy.Web.Models;
using DotNetCoreStudy.Web.services;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Options;

namespace DotNetCoreStudy.Web.Controllers
{
    public class DepartmentController : Controller
    {
        public readonly IDepartmentService _departmentService;
        private readonly IOptions<SystemOptions> _systemOptions;

        public DepartmentController(IDepartmentService departmentService,IOptions<SystemOptions> systemOptions)
        {
            _departmentService = departmentService;
            this._systemOptions = systemOptions;
        }

        [HttpGet]
        public async Task<IActionResult> Index()
        {
            ViewBag.Title = "Department Index";
            var departments = await _departmentService.GetAll();
            return View(departments);
        }

        [HttpGet]
        public IActionResult Add()
        {
            ViewBag.Title = "Add Department";
            return View(new Department());
        }

        /// <summary>
        /// 添加部门
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        [HttpPost]
        public async Task<IActionResult> Add(Department model)
        {
            if (ModelState.IsValid)  //验证model传参是否合法
            {
                await _departmentService.Add(model);
            }
            return RedirectToAction(nameof(Index));
        }

        [HttpGet]
        public IActionResult Update()
        {
            ViewBag.Title = "Edit Department";
            return View(new Department());
        }

        /// <summary>
        /// 更新部门
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        [HttpPost]
        public async Task<IActionResult> Update(Department model)
        {
            if (ModelState.IsValid)
            {
                await _departmentService.Update(model);                
            }
            return RedirectToAction(nameof(Index));
        }
    }
}